#include "WorkThread.h"

WorkThread::WorkThread()
{
    _len = 1000;
    _res = new char[_len];
    _rev = new char[_len];
    _log = new char[_len];
}

WorkThread::~WorkThread()
{
    if(_len > 0)
    {
        _len = 0;
    }

    if(_res != NULL)
    {
        delete [] _res;
        _res = NULL;
    }

    if(_rev != NULL)
    {
        delete [] _rev;
        _rev = NULL;
    }

    if(_log != NULL)
    {
        delete [] _log;
        _log = NULL;
    }
}

void *WorkThread::Process()
{
    WriteLog(NOTICE, "Create work thread id[%d] num[%d] successfully.", (int32)this->GetThreadID(), this->GetThreadNum());

    Socket socket;
    while(ConnPool::Instance()->IsRunning())
    {
        if(!ConnPool::Instance()->PopSocket(socket))
        {
            continue;
        }

        if(!Revceive(socket))
        {
            continue;
        }

        if(!Work())
        {
            continue;
        }

        if(!Response(socket))
        {
            continue;
        }
    }

    WriteLog(NOTICE, "Work thread id[%d] num[%d] exit successfully.", (int32)this->GetThreadID(), this->GetThreadNum());
    return NULL;
}

bool WorkThread::Revceive(Socket socket)
{
    int readLen = sizeof(int);
    int len = SocketRead(socket.fd, _rev, readLen, ConfManager::Instance()->GetReadTimeOut());

    if(len != readLen)
    {
        if(len == -1)
        {
            WriteLog(WARNING, "Socket Read time out.");
        }
        else
        {
            WriteLog(WARNING, "Socket Read Error[%d] Len[%d].", errno, len);
        }

        ConnPool::Instance()->ResetSocket(socket, 0);
        return false;
    }

    _rev[len] = 0;
    WriteLog(NOTICE, "fd:%d ip:%s port:%d threadID:%d rev:%s len:%d\r\n.", socket.fd, socket.ip.c_str(), socket.port, (int32)GetThreadID(), _rev, len);

    return true;
}

bool WorkThread::Work()
{
    int32 gCnt = SocketPool::Instance()->GetGroupCnt();
    for(int32 i=0; i<gCnt; i++)
    {

    }
    return true;
}

bool WorkThread::Response(Socket socket)
{
    int32 len = SocketWrite(socket.fd, _rev, strlen(_rev), ConfManager::Instance()->GetWriteTimeOut());

    if(len != (int32)strlen(_rev))
    {
        if(len == -1)
        {
            WriteLog(WARNING, "Socket Write time out.");
        }
        else
        {
            WriteLog(WARNING, "Socket Write Error[%d] Len[%d].", errno, len);
        }

        ConnPool::Instance()->ResetSocket(socket, 0);
        return false;
    }
    ConnPool::Instance()->ResetSocket(socket, ConfManager::Instance()->GetKeepAlive());

    return true;
}
